plugins["Ban"] = "kontrol_ban"

if SERVER then
	function Ban(pl, cmd, args)
		if !pl:KAdmin() then return end
			
		local admin = pl
		local reason = args[2]
		local length = tonumber(args[3])
			
		if SQL_ACTIVE then
			local target = player.GetByUniqueID(args[1])
			if (target:KAdmin() || target:KModerator()) && !pl:KOwner() then return end
		
			local query = "INSERT INTO kontrol (`id`, `name`, `reason`, `length`, `admin`, `date`, `unbanTime`) VALUES ('" .. target:SteamID() .. "', '" .. tmysql.escape(target:Name()) .. "', '" .. tmysql.escape(reason) .. "', " .. length / 60 .. ", '" .. tmysql.escape(admin:Name()) .. "', '" .. os.date() .. "', " .. os.time() + length .. ")"
			tmysql.query(query)
			
			game.ConsoleCommand("banid " .. length / 60 .. " " .. target:SteamID() .. "\n")
			target:Kick("Banned: " .. length / 60 .. " minutes")
		else
			local target = player.GetByUniqueID(args[1])
			if (target:KAdmin() || target:KModerator()) && !pl:KOwner() then return end
				
			local query = "INSERT INTO kontrol (`id`, `name`, `reason`, `length`, `admin`, `date`, `unbanTime`) VALUES ('" .. target:SteamID() .. "', '" .. target:Name() .. "', '" .. reason .. "', " .. length / 60 .. ", '" .. admin:Name() .. "', '" .. os.date() .. "', " .. os.time() + length .. ")"
			local result = sql.Query(query)
			
			game.ConsoleCommand("banid " .. length / 60 .. " " .. target:SteamID() .. "\n")
			target:Kick("Banned: " .. length / 60 .. " minutes")
		end
	end
	concommand.Add("sv_kontrol_ban", Ban)
	
	hook.Add("PlayerAuthed", "kontrol_ban_ReBanPlayer", function(pl, steam, id)
		if SQL_ACTIVE then
			local query = "SELECT * FROM kontrol WHERE id='" .. steam .. "'"
			tmysql.query(query, function(result, status, error)
				if #result > 0 then
					result = result[1]
					local unbanTime = tonumber(result["unbanTime"])
					
					if unbanTime - os.time() <= 0 && tonumber(result["length"]) != 0 then
						query = "DELETE FROM kontrol WHERE id='" .. steam .. "'"
						tmysql.query(query)
					else
						game.ConsoleCommand("banid " .. math.floor((unbanTime - os.time()) / 60) .. " " .. steam .. "\n")
						pl:Kick("Banned: " .. length / 60 .. " minutes")
					end
				end
			end, 1)
		else
			local query = "SELECT * FROM kontrol WHERE id='" .. steam .. "'"
			local result = sql.Query(query)
			
			if result then
				result = result[1]
				local unbanTime = tonumber(result["unbanTime"])
				
				if unbanTime - os.time() <= 0 && tonumber(result["length"]) != 0 then
					query = "DELETE FROM kontrol WHERE id='" .. steam .. "'"
					result = sql.Query(query)
				else
					game.ConsoleCommand("banid " .. math.floor((unbanTime - os.time()) / 60) .. " " .. steam .. "\n")
					pl:Kick("Banned: " .. length / 60 .. " minutes")
				end
			end
		end
	end)
	
	hook.Add("Initialize", "kontrol_ban_ExpireBans", function()
		if SQL_ACTIVE then
			//Create Ban table if not already exists
			local query = "CREATE TABLE IF NOT EXISTS kontrol (id VARCHAR(255), name TEXT, reason TEXT, length INT, admin TEXT, date TEXT, unbanTime INT)"
			tmysql.query(query)
			
			//Clear expired bans
			local query = "SELECT * FROM kontrol"
			tmysql.query(query, function(result, status, error)
				if #result > 0 then
					for k,v in pairs(result) do
						local unbanTime = tonumber(v["unbanTime"])
						if unbanTime - os.time() <= 0 && tonumber(v["length"]) != 0 then
							game.ConsoleCommand("removeid " .. v["id"] .. "\n")
							query = "DELETE FROM kontrol WHERE id='" .. v["id"] .. "'"
							tmysql.query(query)
						end
					end
				end
			end, 1)
		else
			//Create Ban table if not already exists
			if !sql.TableExists("kontrol") then
				local query = "CREATE TABLE kontrol (id VARCHAR(255), name TEXT, reason TEXT, length INT, admin TEXT, date TEXT, unbanTime INT)"
				local result = sql.Query(query)
			end
		
			//Clear expired bans
			local query = "SELECT * FROM kontrol"
			local result = sql.Query(query)
			if result then
				for k,v in pairs(result) do
					local unbanTime = tonumber(v["unbanTime"])
					if unbanTime - os.time() <= 0 && tonumber(v["length"]) != 0 then
						game.ConsoleCommand("removeid " .. v["id"] .. "\n")
						query = "DELETE FROM kontrol WHERE id='" .. v["id"] .. "'"
						result = sql.Query(query)
					end
				end
			end
		end
	end)
end

if CLIENT then
	function BanMenu(pl, cmd, args)
		local id = args[1]
		
		local menu = vgui.Create("KFrame2")
		menu:SetSize(300, 112)
		menu:SetPos(ScrW() / 2 - 150, ScrH() / 2 - 56)
		menu:SetTitle("Ban Options")
		menu:SetDraggable(true)
		menu:ShowCloseButton(true)
		menu:SetSizable(false)
		menu:MakePopup()
		
		local reason = vgui.Create("DTextEntry", menu)
		reason:SetSize(280, 20)
		reason:SetPos(10, 32)
		reason:SetValue("Reason for Ban")
		
		local choice = "5 Minutes"
		local length = vgui.Create("DMultiChoice", menu)
		length:SetPos(10, 57)
		length:SetSize(280, 20)
		length:SetText("5 Minutes")
		length.OnSelect = function(panel, i, value)
			choice = length:GetOptionText(i)
		end
		length:AddChoice("5 Minutes")
		length:AddChoice("30 Minutes")
		length:AddChoice("1 Hour")
		length:AddChoice("3 Hours")
		length:AddChoice("12 Hours")
		length:AddChoice("1 Day")
		length:AddChoice("2 Days")
		length:AddChoice("3 Days")
		length:AddChoice("5 Days")
		length:AddChoice("1 Week")
		length:AddChoice("2 Weeks")
		length:AddChoice("1 Month")
		length:AddChoice("Permanent")
		
		local accept = vgui.Create("KButton", menu)
		accept:SetSize(100, 20)
		accept:SetPos(100, 82)
		accept:SetText("Accept")
		accept.DoClick = function()
			local banLength = choice
			if banLength == "Permanent" then
				banLength = 0
			elseif banLength == "1 Month" then
				banLength = 40320
			elseif banLength == "2 Weeks" then
				banLength = 20160
			elseif banLength == "1 Week" then
				banLength = 10080
			elseif banLength == "5 Days" then
				banLength = 7200
			elseif banLength == "3 Days" then
				banLength = 4320
			elseif banLength == "2 Days" then
				banLength = 2880
			elseif banLength == "1 Day" then
				banLength = 1440
			elseif banLength == "12 Hours" then
				banLength = 720
			elseif banLength == "3 Hours" then
				banLength = 180
			elseif banLength == "1 Hour" then
				banLength = 60
			elseif banLength == "30 Minutes" then
				banLength = 30
			elseif banLength == "5 Minutes" then
				banLength = 5
			end
			
			local banReason = reason:GetValue()
			if banReason == "Reason for Ban" then banReason = "No reason specified" end
			
			RunConsoleCommand("sv_kontrol_ban", id, banReason, banLength * 60)
			menu:Close()
			RefreshPlayerlist()
		end
	end
	concommand.Add("kontrol_ban", BanMenu)
end